package basemod

import (
	"time"

	"gitee.com/wint/tge/log"
)

// 网络数据接收者
type NetRecver struct {
	NetDataProcessing

	rc 		chan IMsgPack
	fc 		chan func()
}

func (r *NetRecver) Close() {
	close(r.rc)
	close(r.fc)
}

// 响应网络数据
func (r *NetRecver) OnRecv(pack IMsgPack) {
	defer func() {
		if err := recover(); err != nil {
			log.Print("NetRecver ERROR: ", err)
		}
	} ()
	
	if len(r.rc) < 100 {
		r.rc <- pack
	}
}

// 响应回调函数
func (r *NetRecver) OnFunc(fn func()) {
	defer func() {
		if err := recover(); err != nil {
			log.Print("NetRecver ERROR: ", err)
		}
	} ()
	
	if len(r.fc) < 100 {
		r.fc <- fn
	}
}

func (r *NetRecver) excuteFn(fn func()) {
	defer func() {
		if err := recover(); err != nil {
			log.Print("NetRecver ERROR: ", err)
		}
	} ()

	fn()
}

func (r *NetRecver) Run(dt time.Duration) {
	r.rc = make(chan IMsgPack, 100)
	r.fc = make(chan func(), 100)
	if dt > 0 {
		tick := time.Tick(dt)

		for {
			select {
			case <- tick:
				if nil != r.Impl {
					if v, ok := r.Impl.(IUpdater); ok {
						v.Update(dt)
					}
				}
			case msg, ok := <- r.rc:
				if !ok {
					break
				} else {
					code := r.DoMsg(msg)
					if 0 != code {
						msg.GetSes().Send(&Err{msg.GetMsg().GetProtoId(), code, ""})
					}
				}
			case fn, ok := <- r.fc:
				if !ok {
					break
				} else {
					r.excuteFn(fn)
				}
			}
		}
	} else {
		for {
			select {
			case msg, ok := <- r.rc:
				if !ok {
					break
				} else {
					code := r.DoMsg(msg)
					if 0 != code {
						msg.GetSes().Send(&Err{msg.GetMsg().GetProtoId(), code, ""})
					}
				}
			case fn, ok := <- r.fc:
				if !ok {
					break
				} else {
					r.excuteFn(fn)
				}
			}
		}
	}
}